package com.aispeech.astools.recorder;


import android.util.Log;
import com.aispeech.astools.recorder.RecordListener.EVENT;
import java.lang.Thread.State;

/**
 * @author rain  05.15 2019
 */

public class BulkRecord extends HidRecord {

    private final String TAG = "BulkRecord";

    public BulkRecord(int vid, int pid) {
        mVid = vid;
        mPid = pid;
    }

    private Thread mBulkReadThread = new Thread() {
        @Override
        public void run() {
            try {
                if (null == mUsbDeviceConnection || null == mUsbEndpointIn) {
                    Log.e(TAG, "urqReadRunnable,usbRequest mUsbDeviceConnection or mUsbEndpointIn is null ");
                    mListener.onError("mUsbDeviceConnection or mUsbEndpointIn is null");
                    return;
                }

//                int inMax = mUsbEndpointIn.getMaxPacketSize();
//                Log.d(TAG, "bulkReadRunnable: inMax = " + inMax);
                byte[] readBuf = new byte[BULK_TRANSFER_READ_SIZE];

                isWorking = true;
                int bret = 0;
                Log.d(TAG,
                    "mBulkReadThread run: start working ----------------------" + Thread.currentThread().getName() + " : " + Thread.currentThread().getId());
                while (isWorking) {
                    if (isReading) {
                        bret = mUsbDeviceConnection.bulkTransfer(mUsbEndpointIn, readBuf, readBuf.length, BULK_TRANSFER_READ_TIMEOUT);

                        if (bret > 0) {
                            mListener.onBuffer(readBuf);
                        } else {
                            if (bret == -1) {
                                //read time out , cause no voice data input from remote

                            } else {
                                Log.e(TAG, "mHidBulkDataThread: bulkTransfer err: " + bret);
                                mListener.onError("mHidBulkDataThread: bulkTransfer err: " + bret);
                                break;
                            }
                        }
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, "run: " + mUsbDeviceConnection);
                e.printStackTrace();
                mListener.onError(e.toString());
            }

            Log.d(TAG, "mBulkReadThread run: stop working ----------------------" + Thread.currentThread().getName() + " : " + Thread.currentThread().getId());
            isWorking = false;
            isReading = false;
        }
    };


    @Override
    boolean startReadThread() {
        if (mBulkReadThread.getState().equals(State.NEW) | mBulkReadThread.getState().equals(State.TERMINATED)) {
            mListener.onEvent(EVENT.INIT);
            mBulkReadThread.start();
            return true;
        }
        return false;
    }
}
